package com.mxfcode.interceptor;


import com.mxfcode.annotation.LoginRequired;
import com.mxfcode.common.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 检查用户登录状态
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginRequiredInterceptor.class);

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //handler拦截目标
//        if (handler instanceof Class) {//如果拦截的是一个方法
//            HandlerMethod handlerMethod = (HandlerMethod) handler;
//            Method method = handlerMethod.getMethod();
//            //取注解
//            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
//            //如果不为空，则这个方法需要登录才能访问
//            if (loginRequired != null && hostHolder.getUser() == null) {
//                //强制回到登录界面，request.getContextPath()应用路径
//                response.sendRedirect(request.getContextPath() + "/login");
//                return false;
//            }
//        }

        try{
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;

                LoginRequired controllerAnnotation = handlerMethod.getBean().getClass().getDeclaredAnnotation(LoginRequired.class);
                LoginRequired methodAnnotation = handlerMethod.getMethod().getDeclaredAnnotation(LoginRequired.class);

                if ((controllerAnnotation != null || methodAnnotation != null) && hostHolder.getUser() == null) {
                    //强制回到登录界面，request.getContextPath()应用路径
                    response.sendRedirect(request.getContextPath() + "/login");
                    return false;
                }
            }

        }catch (Exception e){
            logger.error("校验登录权限失败，原因是：" + e);
        }

        return true;
    }
}
